package com.yz.jdd.photo.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.darsh.multipleimageselect.models.Image;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.soundcloud.android.crop.Crop;
import com.tencent.smtt.sdk.WebView;
import com.yz.jdd.R;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.FileUtils;
import com.yz.jdd.base.utils.JPGConverter;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.network.RetrofitUtils;
import com.yz.jdd.photo.model.CropOptions;
import com.yz.jdd.photo.model.TContextWrap;
import com.yz.jdd.photo.model.TException;
import com.yz.jdd.photo.model.TExceptionType;
import com.yz.jdd.photo.model.TImage;
import com.yz.jdd.photo.model.TIntentWap;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 工具类
 * Author: JPH
 * Date: 2016/7/26 10:04
 */
public class TUtils {
    private static final String TAG = IntentUtils.class.getName();


    /**
     * 将Image集合转换成Uri集合
     *
     * @param images
     * @return
     */
    public static ArrayList<Uri> convertImageToUri(Context context, ArrayList<Image> images) throws TException {
        ArrayList<Uri> uris = new ArrayList();
        for (Image image : images) {
            uris.add(FileProvider.getUriForFile(context, TConstant.getFileProviderName(context), new File(image.path)));
        }
        return uris;
    }

    /**
     * 将Image集合转换成TImage集合
     *
     * @param images
     * @return
     */
    public static ArrayList<TImage> getTImagesWithImages(ArrayList<Image> images, TImage.FromType fromType) {
        ArrayList<TImage> tImages = new ArrayList();
        for (Image image : images) {
            tImages.add(TImage.of(image.path, fromType));
        }
        return tImages;
    }

    /**
     * 将Uri集合转换成TImage集合
     *
     * @param uris
     * @return
     */
    public static ArrayList<TImage> getTImagesWithUris(ArrayList<Uri> uris, TImage.FromType fromType) {
        ArrayList<TImage> tImages = new ArrayList();
        for (Uri uri : uris) {
            tImages.add(TImage.of(uri, fromType));
        }
        return tImages;
    }

    /**
     * @param contextWrap
     * @param intentWap
     */
    public static void startActivityForResult(TContextWrap contextWrap, TIntentWap intentWap) {
        if (contextWrap.getFragment() != null) {
            contextWrap.getFragment().startActivityForResult(intentWap.getIntent(), intentWap.getRequestCode());
        } else {
            contextWrap.getActivity().startActivityForResult(intentWap.getIntent(), intentWap.getRequestCode());
        }
    }

    /**
     * 安全地发送Intent
     *
     * @param contextWrap
     * @param intentWapList 要发送的Intent以及候选Intent
     * @param defaultIndex  默认发送的Intent
     * @param isCrop        是否为裁切照片的Intent
     * @throws TException
     */
    public static void sendIntentBySafely(TContextWrap contextWrap, List<TIntentWap> intentWapList, int defaultIndex, boolean isCrop) throws TException {
        if (defaultIndex + 1 > intentWapList.size())
            throw new TException(isCrop ? TExceptionType.TYPE_NO_MATCH_PICK_INTENT : TExceptionType.TYPE_NO_MATCH_CROP_INTENT);
        TIntentWap intentWap = intentWapList.get(defaultIndex);
        List result = contextWrap.getActivity().getPackageManager().queryIntentActivities(intentWap.getIntent(), PackageManager.MATCH_ALL);
        if (result.isEmpty()) {
            sendIntentBySafely(contextWrap, intentWapList, ++defaultIndex, isCrop);
        } else {
            startActivityForResult(contextWrap, intentWap);
        }
    }

    /**
     * 拍照前检查是否有相机
     **/
    public static void captureBySafely(TContextWrap contextWrap, TIntentWap intentWap) throws TException {
        List result = contextWrap.getActivity().getPackageManager().queryIntentActivities(intentWap.getIntent(), PackageManager.MATCH_ALL);
        if (result.isEmpty()) {
            Toast.makeText(contextWrap.getActivity(), contextWrap.getActivity().getResources().getText(R.string.tip_no_camera), Toast.LENGTH_SHORT).show();
            throw new TException(TExceptionType.TYPE_NO_CAMERA);
        } else {
            startActivityForResult(contextWrap, intentWap);
        }
    }
    /**
     * 通过第三方工具裁切照片，当没有第三方裁切工具时，会自动使用自带裁切工具进行裁切
     * @param contextWrap
     * @param imageUri
     * @param outPutUri
     * @param options
     */
//    public static void cropWithOtherAppBySafely(TContextWrap contextWrap, Uri imageUri, Uri outPutUri, CropOptions options){
//        Intent nativeCropIntent=IntentUtils.getCropIntentWithOtherApp(imageUri, outPutUri,options);
//        List result=contextWrap.getActivity().getPackageManager().queryIntentActivities(nativeCropIntent,PackageManager.MATCH_ALL);
//        if (result.isEmpty()){
//            cropWithOwnApp(contextWrap,imageUri,outPutUri,options);
//        }else {
////            try {
////                imageUri=Uri.fromFile(new File(TUriParse.getFilePathWithDocumentsUri(imageUri,contextWrap.getActivity())));
////            } catch (TException e) {
////                e.printStackTrace();
////            }
//            startActivityForResult(contextWrap,new TIntentWap(IntentUtils.getCropIntentWithOtherApp(imageUri, outPutUri,options), TConstant.RC_CROP));
//        }
//    }

    /**
     * 通过TakePhoto自带的裁切工具裁切图片
     *
     * @param contextWrap
     * @param imageUri
     * @param outPutUri
     * @param options
     */
    public static void cropWithOwnApp(TContextWrap contextWrap, Uri imageUri, Uri outPutUri, CropOptions options) {
        if (options.getAspectX() * options.getAspectY() > 0) {
            if (contextWrap.getFragment() != null) {
                Crop.of(imageUri, outPutUri).withAspect(options.getAspectX(), options.getAspectY()).start(contextWrap.getActivity(), contextWrap.getFragment());
            } else {
                Crop.of(imageUri, outPutUri).withAspect(options.getAspectX(), options.getAspectY()).start(contextWrap.getActivity());
            }
        } else if (options.getOutputX() * options.getOutputY() > 0) {
            if (contextWrap.getFragment() != null) {
                Crop.of(imageUri, outPutUri).withMaxSize(options.getOutputX(), options.getOutputY()).start(contextWrap.getActivity(), contextWrap.getFragment());
            } else {
                Crop.of(imageUri, outPutUri).withMaxSize(options.getOutputX(), options.getOutputY()).start(contextWrap.getActivity());
            }
        } else {
            if (contextWrap.getFragment() != null) {
                Crop.of(imageUri, outPutUri).asSquare().start(contextWrap.getActivity(), contextWrap.getFragment());
            } else {
                Crop.of(imageUri, outPutUri).asSquare().start(contextWrap.getActivity());
            }
        }
    }

    /**
     * 是否裁剪之后返回数据
     **/
    public static boolean isReturnData() {
        String release = Build.VERSION.RELEASE;
        int sdk = Build.VERSION.SDK_INT;
        Log.i(TAG, "release:" + release + "sdk:" + sdk);
        String manufacturer = Build.MANUFACTURER;
        if (!TextUtils.isEmpty(manufacturer)) {
            if (manufacturer.toLowerCase().contains("lenovo")) {//对于联想的手机返回数据
                return true;
            }
        }
//        if (sdk>=21){//5.0或以上版本要求返回数据
//            return  true;
//        }
        return false;
    }

    /**
     * 显示圆形进度对话框
     *
     * @param activity
     * @param progressTitle 显示的标题
     * @return
     * @author JPH
     * Date 2014-12-12 下午7:04:09
     */
    public static ProgressDialog showProgressDialog(final Activity activity,
                                                    String... progressTitle) {
        if (activity == null || activity.isFinishing()) return null;
        String title = activity.getResources().getString(R.string.tip_tips);
        if (progressTitle != null && progressTitle.length > 0)
            title = progressTitle[0];
        ProgressDialog progressDialog = new ProgressDialog(activity);
        progressDialog.setTitle(title);
        progressDialog.setCancelable(false);
        progressDialog.show();
        return progressDialog;
    }

    /**
     * 图片大小单位换算
     *
     * @param size
     * @param unit 单位 kb or mb
     * @return
     */
    public static int sizeConverter(int size, String unit) {
        if ("b".equalsIgnoreCase(unit)) {
            return size * 1024;
        } else if ("m".equalsIgnoreCase(unit)) {
            return (int) (size / 1024);
        }
        return size;
    }

    /**
     * 上传多张图片及参数
     *
     * @param url      URL地址
     * @param filePath 图片路径
     */
    public static void uploadPictures(final WebView webView, final String url, String filePath, Object data) {
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        URL tempUrl;
        LogUtils.d("======= filepath :: " + filePath);
        try {
            if (!TextUtils.isEmpty(filePath)) {
                tempUrl = new URL(filePath);
                if (FileUtils.isExists(tempUrl.getPath())) {
                    File file = new File(tempUrl.getPath());
                    Log.d("shibin","file path ::  " + file.getPath() + "tempUrl path:: "+tempUrl.getPath());
                    String prefix = FileUtils.getFilePrefixName(file);
                    if ("jpg".equalsIgnoreCase(prefix)) {
                        multipartBodyBuilder.addFormDataPart("file", URLEncoder.encode(file.getName()), RequestBody.create(MediaType.parse("image/jpg"), file));
                    } else if ("jpeg".equalsIgnoreCase(prefix)) {
                        multipartBodyBuilder.addFormDataPart("file",  URLEncoder.encode(file.getName()), RequestBody.create(MediaType.parse("image/jpeg"), file));
                    } else {
                        File newFile = JPGConverter.convertToJpg(file.getPath(), getPicName(file.getPath()) + ".jpg");
                        Log.d("shibin","new file "+ newFile.getPath());
                        multipartBodyBuilder.addFormDataPart("file",  URLEncoder.encode(newFile.getName()), RequestBody.create(MediaType.parse("image/jpg"), newFile));
                    }
                }

                if (data != null) {
                    Map<String, String> map = new Gson().fromJson(data.toString(), new TypeToken<HashMap<String, String>>() {
                    }.getType());
                    if (map != null && map.size() > 0) {
                        for (String key : map.keySet()) {
                            LogUtils.d("key :: " + key + " value :: " + map.get(key));
                            multipartBodyBuilder.addFormDataPart(key, map.get(key));
                        }
                    }
                }
                //构建请求体
                RequestBody requestBody = multipartBodyBuilder.build();
                Request.Builder RequestBuilder = new Request.Builder();
                RequestBuilder.url(url);
                RequestBuilder.post(requestBody);
                final Request request = RequestBuilder.build();
                RetrofitUtils.getOkHttpClient().newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
//                        Log.e("lkf","uploadPictures------onFailure");
                        RxBus.getInstance().send(Events.EVENT_UPLOADPICTURE_RESULT, "");
                        call.cancel();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String str = response.body().string();
                        RxBus.getInstance().send(Events.EVENT_UPLOADPICTURE_RESULT, str);
                        call.cancel();
                    }
                });

            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }


    public static String getPicName(String path) {
        String temp[] = path.split("\\.");
        String fileName = "";
        if (temp.length > 0) {
            fileName = temp[0];
        }
        return fileName;
    }
}
